package com.demo.webapp.ui.menu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContext;

import com.demo.webapp.ui.DisplayerConfig;
import com.demo.webapp.ui.RepositoryBuilderBase;
import com.demo.webapp.ui.config.ComponentRulesModule;
import com.demo.webapp.ui.displayer.DisplayerMapping;
import com.demo.webapp.ui.menu.displayer.VelocityMenuDisplayer;

/**
 * Menu组件的持久化对象生成器类
 * <br/>默认读取classpath:/menu-config.xml配置文件
 * @author ryuu.kk
 *
 */
public class MenuRepositoryBuilder extends RepositoryBuilderBase {

	/**
	 * 默认文件装载策略配置文件
	 */
	public static final String[] REPOSITORY_MENU_BASENAME = {"classpath:com/demo/webapp/ui/menu/digester-menu.xml"};
	
	/**
	 * MENU组件持久化资源对象
	 * 所有MENU组件都存放于此
	 */
	private MenuRepositoryResource menuRepository;
	
	/**
	 * 初始化MenuRepositoryBuilder数据
	 */
	private void init() {
		menuRepository = new MenuRepositoryResource();
		//使用默认配置文件位置
		if (getBaseNames() == null || getBaseNames().length ==0) {
			setBaseNames(MenuRepositoryBuilder.REPOSITORY_MENU_BASENAME);
		}
	}
	@Override
	public void beforeLoad(ComponentRulesModule module) {
		//数据初始化
		init();
		
		//设置栈顶对象,XML文件将操作这个对象将属性注入
		push(this.menuRepository);
		log.debug(module);
	}

	@Override
	public void afterLoad(ServletContext servletContext) {
		log.debug("after load.");
		DisplayerMapping mapping = this.menuRepository.getMapping();
		if (mapping != null) {
			List<DisplayerConfig> dispConfigs = mapping.getDisplayerConfig();
			if (dispConfigs != null && dispConfigs.size() > 0) {
				for (DisplayerConfig config : dispConfigs) {
					if ("com.demo.webapp.ui.menu.displayer.VelocityMenuDisplayer".equals(config.getType())) {
						if (servletContext == null) {
					        log.error("ServletContext not set - can't initialize Velocity");
						} else {
							VelocityMenuDisplayer.initialize(servletContext);
						}
					}
				}
			}
		}
        //将持久对象MenuRepositoryResource放入Servlet容器上下文中
		servletContext.setAttribute(MenuRepositoryResource.MENU_REPOSITORY_KEY, pop());
	}
	public void setBaseRepository(MenuRepositoryResource menuRepository) {
		this.menuRepository = menuRepository;
	}
	
	@Override
	public void setConfig(String conf) {
		String[] configs = new String[]{};
		if (conf != null ) {
			configs = conf.split(",");
		}
		// 本地配置
		if (configs.length == 0) {
			// 使用默认配置
			configs = new String[] {"classpath:/menu-config.xml"};
		}
		super.setConfigs(configs);
	}
	
	@Override
	public void setConfigs(String[] configs) {
		super.setConfigs(configs);
	}
}